import { defineStore } from "pinia";
import { ElMessage } from "element-plus";
import $ from "@axios/api/login/index";
import * as dd from "dingtalk-jsapi";
import { useRouter } from "vue-router";

const login = defineStore("login", {
  state: () => ({
    P_show: false,
    goHome: "/supplierpro",
    R: useRouter(),
    userName: sessionStorage.getItem("user") || "",
  }),
  actions: {
    // 桥梁
    Hp_Login() {
      if (sessionStorage.getItem("token")) this.P_show = true;
      this.R.push("/claim");
      var _this = this;
      dd.ready(function () {
        dd.runtime.permission.requestAuthCode({
          corpId: __DINGTALK_APP_ID__, // 企业id

          onSuccess: async function (info) {
            console.log("钉钉code", info);

            await $.Hp_Login({ code: info.code }).then(
              (res) => {
                console.log("token", res);
                if (res.length) {
                  sessionStorage.setItem("token", res);
                  _this.Hp_UserInfo();
                } else {
                  ElMessage.error("token授权失败，请稍后重试");
                }
              },
              (err) => {
                ElMessage.error("网络异常请稍后");
              }
            );
            console.log(info.code);
          },
          onFail: function (fail) {
            console.log("error", fail);
            // return "请登录"
            return Promise.reject(fail);
          },
        });
      });
    },
    async Hp_UserInfo() {
      if (sessionStorage.getItem("info")) {
        this.userName = sessionStorage.getItem("user");
        return (this.P_show = true);
      }
      await $.Hp_UserInfo().then(
        (res) => {
          if (res.code === 200) {
            sessionStorage.setItem("info", JSON.stringify(res.data));
            sessionStorage.setItem("roleName", JSON.stringify(res.data.roles));

            this.userName = res.data.info.userName;
            sessionStorage.setItem("user", this.userName);
            sessionStorage.setItem(
              "roles",
              res.data.roles.map((e) => e.roleName).join(",")
            );

            const list = res.data.roles.map((e) => e.roleId);

            sessionStorage.setItem(
              "jurisdiction",
              list.includes(1) ||
                list.includes("ff91c1756fe636e3f7ef8e689fd1398a")
            );
            this.P_show = true;
            this.R.push(this.goHome);
          } else {
            ElMessage.error("权限获取失败，请稍后重试");

            if (__REDIRECT__ == "NO") {
              this.R.push("/login");
            } else {
              window.location.href = __REDIRECT__;
            }
          }
        },
        (err) => {
          ElMessage.error("当前网络异常，请稍后重试");
        }
      );
    },
    // async Hp_GetUser() {
    //   if (sessionStorage.getItem("all_user")) {

    //     return;
    //   }
    //   await $.Hp_GetUser().then(
    //     (res) => {
    //       if (res.code === 200) {
    //         sessionStorage.setItem(
    //           "all_user",
    //           JSON.stringify(res.data.records)
    //         );
    //       } else {
    //         ElMessage.error("公司人员,获取失败");
    //       }
    //     },
    //     (err) => {
    //       ElMessage.error("当前网络异常，请稍后重试");
    //     }
    //   );
    // },
  },
});

export default login;
